package cn.gzmli.dtt.common.service.log;

import cn.gzmli.dtt.common.entity.PageInfo;
import cn.gzmli.dtt.common.entity.User;
import cn.gzmli.dtt.common.entity.UserOnlineLog;
import cn.gzmli.dtt.common.utils.BaseService;
import cn.gzmli.dtt.common.utils.BaseUtil;
import cn.gzmli.dtt.common.utils.DateUtils;
import com.xiaoleilu.hutool.util.StrUtil;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Descript
 * @Author xsx
 * @Date 2018/3/21
 */
@Service
@Transactional
public class UserOnlineLogService extends BaseService<UserOnlineLog> {
    /**
     * 总体列表
     * @param condition 查询条件
     * @param pageInfo 分页对象
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> getByCondition(Map<String, Object> condition, PageInfo pageInfo) throws Exception{
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT id,userId,loginName,userName,departmentId,departmentName,MAX(lastTime) AS lastTime,SUM(onlineTime) AS onlineTime ")
            .append("FROM user_online_log WHERE 1=1 AND userId<>1");
        return BaseUtil.getData(sql, condition, pageInfo, this.getDao(), "userId", "onlineTime", false);
    }

    /**
     * 部门统计时长
     * @param condition 查询条件
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> getByTime(Map<String, Object> condition) throws Exception{
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT departmentId,departmentName,SUM(onlineTime) AS onlineTime FROM user_online_log ul LEFT JOIN department d ON  ul.departmentId=d.id WHERE 1=1 AND departmentId<>1 ");
        return BaseUtil.getData(sql, condition, this.getDao(), "departmentId", "d.orderNo", true);
    }

    /**
     * 部门统计人数
     * @param condition 查询条件
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> getByCount(Map<String, Object> condition) throws Exception{
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT departmentId,departmentName,COUNT(DISTINCT userId) AS count FROM user_online_log ul LEFT JOIN department d ON  ul.departmentId=d.id WHERE 1=1 AND departmentId<>1 ");
        return BaseUtil.getData(sql, condition, this.getDao(), "departmentId", "d.orderNo", true);
    }

    public void saveOrUpdate(String sessionId, User user) throws Exception{
        final String query = "SELECT * FROM user_online_log WHERE userId=? AND lastSessionId=?";
        Map<String, Object> data;
        try{
            data = this.getDao().getJdbcTemplate().queryForMap(query,user!=null?user.getId():"0", sessionId);
        }catch (EmptyResultDataAccessException e){
            data = null;
        }
        if (data==null){
            final String insert = "INSERT INTO user_online_log(userId,loginName,userName,departmentId,departmentName,lastSessionId) VALUES(?,?,?,?,?,?)";
            this.getDao().getJdbcTemplate().update(insert, user.getId(), user.getUserName(), user.getName(), user.getDepartment().getId(), user.getDepartment().getName(), sessionId);
        }else{
            Date time = (Date) data.get("lastTime");
            Calendar start = Calendar.getInstance();
            start.setTime(time);
            double online = ((Calendar.getInstance().getTimeInMillis()-start.getTimeInMillis())/60/60/1000.00d);
            final String update = "UPDATE user_online_log SET lastSessionId=?,lastTime=?,onlineTime=(onlineTime+?) WHERE id=?";
            this.getDao().getJdbcTemplate().update(update, sessionId, new Date(), online, data.get("id"));
        }
    }

    public void updateOnlineTime(String sessionId, User user){
        final String query = "SELECT * FROM user_online_log WHERE userId=? AND lastSessionId=?";
        Map<String, Object> data;
        try{
            data = this.getDao().getJdbcTemplate().queryForMap(query, user.getId(), sessionId);
        }catch (EmptyResultDataAccessException e){
            data = null;
        }
        if (data!=null){
            Date time = (Date) data.get("lastTime");
            Calendar start = Calendar.getInstance();
            start.setTime(time);
            double online = ((Calendar.getInstance().getTimeInMillis()-start.getTimeInMillis())/60/60/1000.00d);
            final String update = "UPDATE user_online_log SET onlineTime=(onlineTime+?) WHERE id=?";
            this.getDao().getJdbcTemplate().update(update, online, data.get("id"));
        }
    }


}
